package com.afs.electronicforensics.fragment;

import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.afs.electronicforensics.adapter.AlbumLocalAdapter;
import com.afs.electronicforensics.entity.FileInfo;
import com.afs.electronicforensics.activity.R;
import com.afs.electronicforensics.utils.Constants;
import com.afs.electronicforensics.utils.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AlbumLocalFragment extends Fragment {

    AlbumLocalAdapter albumRvAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.recyclerview_card, container, false);
        ArrayList<FileInfo> items = new ArrayList<>();

        EditText searchText = root.findViewById(R.id.search_text);
        ImageView searchBtn = root.findViewById(R.id.search_btn);

        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ Constants.USER_PATH.getImagePath();
        File filepath = new File(path);
        File[] files = filepath.listFiles();

        if (null != files) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                items.add(new FileInfo(fileName,path+fileName));
            }
        }
        RecyclerView recyclerView = root.findViewById(R.id.recyclerview_card);
        StaggeredGridLayoutManager layoutManager=new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);


        albumRvAdapter = new AlbumLocalAdapter(getActivity(),items);
        recyclerView.setAdapter(albumRvAdapter);



        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = searchText.getText().toString().trim();
                if(name != null && !("").equals(name)){
                    ArrayList<FileInfo> resultItems = FileUtil.search(name, items);
                    albumRvAdapter = new AlbumLocalAdapter(getActivity(),resultItems);
                    recyclerView.setAdapter(albumRvAdapter);
                }else {
                    albumRvAdapter = new AlbumLocalAdapter(getActivity(),items);
                    recyclerView.setAdapter(albumRvAdapter);
                }
            }
        });

        return root;
    }



}
